package controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import model.ClientModel;
import view.MainWindow;

public class ClientController {

	ClientModel newClient = new ClientModel();
	public String id_client;
	public int discounter;

	public void createClient() {

		
		
		String family = MainWindow.getTextField();

		String name = MainWindow.getTextField_1();

		String surname = MainWindow.getTextField_2();

		int phoneNum = Integer.parseInt(MainWindow.getTextField_3());

		newClient.FIO = family.concat(" ").concat(name).concat(" ")
				.concat(surname);

		newClient.phoneNumber = phoneNum;
		newClient.feedDO = 0;

		try {
			Connection conn = DatabaseConnection.getInstance().getConnection();
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(String.format(
					"SELECT * FROM clients WHERE fio=\"%s\" AND tel=%s",
					newClient.FIO, Integer.toString(newClient.phoneNumber)));

			if (rs.next()) {
				newClient.discount = rs.getInt("discount");
				discounter = newClient.discount;
				newClient.feedDO = rs.getInt("feed_do") + 1;
				id_client = rs.getString("id_client");
				
				int tempDiscount = newClient.feedDO/10;
				if (tempDiscount>15)
					tempDiscount = 15;
				newClient.discount = tempDiscount;
				
				PreparedStatement ps = conn.prepareStatement(String.format(
						"UPDATE clients SET feed_do=%s, discount=%s WHERE id_client=%s",
						Integer.toString(newClient.feedDO), Integer.toString(newClient.discount), id_client));
				ps.executeUpdate();
			} else {
				newClient.feedDO++;
				PreparedStatement ps = conn
						.prepareStatement(String
								.format("INSERT INTO clients VALUES (NULL, \"%s\", %s, %s, 0, %s)",
										newClient.FIO,
										Integer.toString(newClient.discount),
										Integer.toString(newClient.feedDO),
										Integer.toString(newClient.phoneNumber)));
				ps.executeUpdate();
				
				Statement st2 = conn.createStatement();
				ResultSet rs2 = st2.executeQuery(String.format(
						"SELECT * FROM clients WHERE fio=\"%s\" AND tel=%s",
						newClient.FIO, Integer.toString(newClient.phoneNumber)));
				rs2.next();
				id_client = rs.getString("id_client");
				st2.close();
				rs2.close();
				
			}
			rs.close();
			st.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
